package cn.mastor.pet.service.impl;

import cn.mastor.basic.config.BussinessException;
import cn.mastor.basic.util.*;
import cn.mastor.order.domain.OrderPetAcquisition;
import cn.mastor.order.service.IOrderPetAcquisitionService;
import cn.mastor.org.domain.Employee;
import cn.mastor.org.domain.Shop;
import cn.mastor.org.mapper.EmployyMapper;
import cn.mastor.org.mapper.ShopMapper;
import cn.mastor.pet.domain.RejectLog;
import cn.mastor.pet.domain.SearchMasterMsg;
import cn.mastor.pet.domain.SearchMasterMsgAuditLog;
import cn.mastor.pet.dto.AcceptDto;
import cn.mastor.pet.mapper.RejectLogMapper;
import cn.mastor.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.mastor.pet.mapper.SearchMasterMsgMapper;
import cn.mastor.pet.query.SearchMasterMsgQuery;
import cn.mastor.pet.service.ISearchMasterMsgService;
import cn.mastor.basic.service.impl.BaseServiceImpl;
import cn.mastor.user.domain.Logininfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.HttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2022-11-01
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    SyncMessageListener syncMessageListener;
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    EmployyMapper employyMapper;
    @Autowired
    RejectLogMapper rejectLogMapper;
    @Autowired
    IOrderPetAcquisitionService orderPetAcquisitionService;
    @Autowired
    ProducerMsg producerMsg;
    @Override
    public void publish(SearchMasterMsg searchMasterMsg) {
        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        StringBuffer sb = new StringBuffer();
        sb.append(searchMasterMsg.getAddress())
          .append(searchMasterMsg.getName());
        if (StringUtils.isEmpty(searchMasterMsg.getName())|| StringUtils.isEmpty(searchMasterMsg.getAddress()) || !BaiduAuditUtils.TextCensor(String.valueOf(sb))){
            searchMasterMsg.setState(0);
            searchMasterMsgMapper.add(searchMasterMsg);
            log.setState(0);
            log.setNote("名字或地址不能为空,检查名字或地址是否合规");
            searchMasterMsg.setNote("名字或地址不能为空,检查名字或地址是否合规");
            searchMasterMsgMapper.add(searchMasterMsg);
            log.setMsgId(searchMasterMsg.getId());
            log.setAuditTime(new Date());
            searchMasterMsgAuditLogMapper.add(log);
            throw new BussinessException("名字或地址不能为空,检查名字或地址是否合规");
        }else{
            log.setState(1);
            searchMasterMsg.setNote("审核成功");
            log.setNote("审核成功");
            List<Shop> all = shopMapper.findAll();
            Shop shop = DistanceUtil.getNearestShop(DistanceUtil.getPoint(searchMasterMsg.getAddress()), all);
            if (shop!=null) {
                searchMasterMsg.setShopId(shop.getId());
            }
            searchMasterMsg.setState(1);
            searchMasterMsgMapper.add(searchMasterMsg);
            log.setMsgId(searchMasterMsg.getId());
            log.setAuditTime(new Date());
            searchMasterMsgAuditLogMapper.add(log);
        }
    }

    @Override
    public PageList querySearchMasterMsg(SearchMasterMsgQuery query) {
        Integer totals = searchMasterMsgMapper.queryBysearchMasterMsgCount(query);
        if (null == totals || 0 == totals){
            return new PageList<>(0,new ArrayList<>());
        }
        // 查询数据
        List<SearchMasterMsg> searchMasterMsgs = searchMasterMsgMapper.querySearchMasterMsg(query);
        //方到返回里面
        return new PageList<>(totals,searchMasterMsgs);
    }

    @Override
    public AjaxResult accept(AcceptDto acceptDto) {
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(acceptDto.getMsgId());
        if (null == searchMasterMsg){
            throw new BussinessException("该消息为空，请重新操作");
        }
        synchronized (searchMasterMsg.getId()){
            Employee employee = employyMapper.findById(acceptDto.getHandler());
            if (null==employee){
                throw new BussinessException("该管理员不存在");
            }
            if (searchMasterMsg.getState()==1&&searchMasterMsg.getShopId().equals(employee.getShopId())){
                // 4.修改寻主消息状态为2
                searchMasterMsg.setState(2);
                searchMasterMsgMapper.update(searchMasterMsg);
                // 5.生成收购单
                initOrderPetAcquisition(acceptDto, searchMasterMsg, employee);
            }
        }
        return AjaxResult.me().success();
    }

    @Override
    public AjaxResult reject(Long id,HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employyMapper.findBylogininfoId(logininfo.getId());
        Long shopId = employee.getShopId();
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(id);
        searchMasterMsg.setShopId(null);
        searchMasterMsg.setState(1);
        searchMasterMsgMapper.update(searchMasterMsg);
        System.out.println(searchMasterMsgMapper.findById(id));
        RejectLog rejectLog = new RejectLog();
        rejectLog.setShopId(Math.toIntExact(shopId));
        Date date = new Date();
        rejectLog.setTime(date);
        Shop shop = shopMapper.findById(shopId);
        rejectLog.setNote(shop.getName()+"于"+date+"拒单");
        rejectLogMapper.add(rejectLog);
        return AjaxResult.me().success();
    }

    /**
     * 生成订单
     * @param acceptDto
     * @param searchMasterMsg
     * @param employee
     */
    private void initOrderPetAcquisition(AcceptDto acceptDto, SearchMasterMsg searchMasterMsg, Employee employee) {
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(acceptDto.getHandler());
        orderPetAcquisition.setOrderSn(orderSn);
        orderPetAcquisition.setDigest(acceptDto.getNote());
        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis() + 3 * 24 * 60 * 60 * 1000));
//        Message message = new Message("hello_topic", "hello_tags", "烦烦烦".getBytes(StandardCharsets.UTF_8));

        producerMsg.syncSendDelayMessage(orderSn);
        syncMessageListener.onMessage("");
        orderPetAcquisition.setState(0);
//        System.out.println("看看效果");
        // 此時的钱就是用户发布的价格，要注意此金额不是最终金额，要以实际交易金额为准
        orderPetAcquisition.setPrice(new BigDecimal(searchMasterMsg.getPrice()));
        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
        orderPetAcquisition.setShopId(employee.getShopId());
        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
        orderPetAcquisition.setEmpId(employee.getId());
        orderPetAcquisition.setSearchMasterMsgId(searchMasterMsg.getId());
        orderPetAcquisitionService.add(orderPetAcquisition);
    }
}
